package com.bee.bootstrap.user.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.bee.bootstrap.user.entity.User;
import com.bee.bootstrap.user.service.IUserService;
import com.bee.common.core.jsonview.PrivilegeView;
import com.bee.common.core.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jose4j.lang.JoseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liekkas
 * @since 2018-04-09
 */
@RestController
@RequestMapping("/users")
@Api(value = "/users", description = "用户管理")
public class UserController {

    @Autowired
    private IUserService userServiceImpl;

    @GetMapping("")
    @ApiOperation(value="获取用户分页对象", notes="获取用户分页对象")
    @PrivilegeView
    public Result findUsers(@ModelAttribute User user, Page<User> page){
        return userServiceImpl.findPageView(page,user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用戶")
    public Result deleteUser(@PathVariable(required = true,value ="id") long id){
        return userServiceImpl.deleteUserById(id);
    }

    @PutMapping("/{id}")
    public Result updateUser(@Valid @RequestBody User user, @PathVariable(required = true,value ="id") long id, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return userServiceImpl.updateUser(user);
    }

    @PostMapping("")
    public Result createUser(@Valid @RequestBody User user,BindingResult bindingResult) throws JoseException {
        if(bindingResult.hasErrors()){
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return userServiceImpl.addUser(user);
    }
	
}
